#!/bin/bash -e

# This script is defined for compatibility with the Compiler Unit Tests.
# It should not be used for other purposes.
# Specifically it disables dumping stack traces on unhandled exceptions.
# Use build/bin/skip_to_js && tools/run_js directly instead.

# Arguments: sk-files [-- sk-args...]

RUNTIME_DIR=${RUNTIME_DIR:-$(dirname $(dirname "${0}"))}
SOURCE_DIR=${SOURCE_DIR:-$(dirname $(dirname ${RUNTIME_DIR}))}
BUILD_DIR=${BUILD_DIR:-${SOURCE_DIR}/build}
BINARY_DIR=${BINARY_DIR:-${BUILD_DIR}/bin}
TMPDIR=${BUILD_DIR}/tmp
JSLIB=${JSLIB:-${RUNTIME_DIR}/js}

# Get SK files, advance args past optional --
SK_FILES=()
while [[ $# -ge 1 ]]; do
  ARG="$1"
  shift
  if [ $ARG == '--profile' ]; then
    shift
  elif [ $ARG == '--' ]; then
    break
  else
    SK_FILES+=($ARG)
  fi
done

mkdir -p ${TMPDIR}
OUTPUT=$(mktemp -d "${TMPDIR}/skip_js_self_exec.XXXXXXXXXX")

# Increase the stack size in case we are compiling something very large.
softlimit=32768
hardlimit=`ulimit -Hs`
if [ "$hardlimit" != "unlimited" ] && (( $softlimit > $hardlimit )); then
    softlimit=$hardlimit
fi
ulimit -s $softlimit

${SOURCE_DIR}/tools/run_js_file --no-unhandled-exception-stack ${BINARY_DIR}/skip_to_js.js --output "$OUTPUT/sk.js" --no-source-map "${SK_FILES[@]}"
${SOURCE_DIR}/tools/run_js --no-unhandled-exception-stack "$OUTPUT" "$@"

# Clean up after ourselves.
if [ -z "$KEEP_TEMP" ]; then
    rm -rf "$OUTPUT"
fi
